package com.ubb.damate.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.ubb.damate.model.RunTimesModel;
import com.ubb.damate.model.UserEvent;
import com.ubb.damate.model.User;
import com.ubb.damate.service.RunTimesServiceLocal;
import com.ubb.damate.service.RunTimesServiceRemote;
import com.ubb.damate.service.UserServiceLocal;
import com.ubb.damate.util.DateUtils;

/** Session Bean implementation class RunTimesService */
@Stateless
public class RunTimesService implements RunTimesServiceRemote, RunTimesServiceLocal {

	@PersistenceContext(unitName = "damate-pu")
	private EntityManager	em;
	
	@EJB(beanName = "UserService")
	private UserServiceLocal	userService;
	
	public Map<User, RunTimesModel> getStats()
	{
		Map<User, RunTimesModel> result = new HashMap<User, RunTimesModel>();
		List<User> users = userService.allUser();
		for (User user : users) {
			result.put(user, getStats(user.getUsername()));
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public RunTimesModel getStats(String username) {
		CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
		CriteriaQuery<UserEvent> criteriaQuery = criteriaBuilder.createQuery(UserEvent.class);
		Root<UserEvent> from = criteriaQuery.from(UserEvent.class);
		Predicate condition = criteriaBuilder.equal(from.get("id").get("username"), username);
		criteriaQuery.where(condition);
		Query query = em.createQuery(criteriaQuery);

		List<UserEvent> successEvents = (List<UserEvent>) query.getResultList();
		List<Integer> nrOfSuccess = new ArrayList<Integer>();
		List<Integer> nrOfFail = new ArrayList<Integer>();
		for (int i = 0; i < 12; i++) {
			nrOfSuccess.add(0);
			nrOfFail.add(0);
		}

		for (UserEvent event : successEvents) {
			int i = DateUtils.getMonthFromDate(event.getId().getEventdate());
			if (event.getId().getEventname().equals("RunSuccess")) {
				nrOfSuccess.set(i, nrOfSuccess.get(i) + Integer.parseInt(event.getEventvalue()));
			} else {
				nrOfFail.set(DateUtils.getMonthFromDate(event.getId().getEventdate()), nrOfFail.get(i) + Integer.parseInt(event.getEventvalue()));
			}
		}

		RunTimesModel runTimesModel = new RunTimesModel();
		runTimesModel.setNrOfSuccess(nrOfSuccess);
		runTimesModel.setNrOfFail(nrOfFail);

		return runTimesModel;
	}
}